package com.xinghuo.building.ui.base

import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LiveData
import androidx.viewbinding.ViewBinding
import com.google.android.material.snackbar.Snackbar
import com.product.xlogger.ILogger
import com.product.xlogger.XLogger
import com.xinghuo.building.utils.SingleEvent
import com.xinghuo.building.utils.showToast

/**
 * Created by chendaning
 */


abstract class BaseActivity<T: ViewBinding>: AppCompatActivity() {
    protected lateinit var mBindView: T
    abstract fun observeViewModel()
    protected abstract fun getLayoutId(): Int
    protected abstract fun getViewModel(): BaseViewModel?

    lateinit var logger: ILogger
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = resources.getColor(android.R.color.white)
        }
        logger = XLogger.getInstance()
        this.mBindView  = DataBindingUtil.setContentView(this, getLayoutId())

        observeViewModel()
        getViewModel()?.let { observeToast(it.showToast) }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    protected fun observeToast(event: LiveData<SingleEvent<Any>>) {
        mBindView.root.showToast(this, event, Snackbar.LENGTH_LONG)
    }
}
